<template>
  <div class="electronic-signature-page">
    <div class="page-header">
      <h2>电子签章系统</h2>
      <div class="header-actions">
        <el-button type="primary" icon="Plus" @click="showSignDialog = true">发起签署</el-button>
        <el-button icon="Setting">签章管理</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #e8f4ff">
            <el-icon color="#409eff" :size="24"><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalDocuments }}</div>
            <div class="stat-label">待签文档</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #fff5e8">
            <el-icon color="#fa8c16" :size="24"><Edit /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.myPendingSignatures }}</div>
            <div class="stat-label">待我签署</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #e8fff3">
            <el-icon color="#52c41a" :size="24"><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.completedSignatures }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #fff0f0">
            <el-icon color="#ff4d4f" :size="24"><Close /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.rejectedSignatures }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主内容 -->
    <el-card class="main-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 待我签署 -->
        <el-tab-pane label="待我签署" name="pending">
          <el-table :data="pendingList" stripe>
            <el-table-column prop="documentName" label="文档名称" width="200" />
            <el-table-column prop="initiator" label="发起人" width="120" />
            <el-table-column prop="documentType" label="文档类型" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.documentType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sendTime" label="发送时间" width="180" />
            <el-table-column prop="deadline" label="截止时间" width="180" />
            <el-table-column prop="signType" label="签署方式" width="120">
              <template #default="{ row }">
                <el-tag type="primary">{{ row.signType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="urgency" label="紧急程度" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getUrgencyType(row.urgency)">{{ row.urgency }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="previewDocument(row)">预览</el-button>
                <el-button link type="success" @click="signDocument(row)">签署</el-button>
                <el-button link type="danger" @click="rejectDocument(row)">拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 我发起的 -->
        <el-tab-pane label="我发起的" name="initiated">
          <el-table :data="initiatedList" stripe>
            <el-table-column prop="documentName" label="文档名称" width="200" />
            <el-table-column prop="documentType" label="文档类型" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.documentType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发起时间" width="180" />
            <el-table-column prop="signProgress" label="签署进度" width="200" align="center">
              <template #default="{ row }">
                <el-progress :percentage="row.signProgress" />
                <span style="font-size: 12px; color: #909399">
                  {{ row.signedCount }}/{{ row.totalSigners }}人已签署
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewProgress(row)">进度</el-button>
                <el-button link type="success" @click="downloadDocument(row)">下载</el-button>
                <el-button link type="warning" @click="urgeSign(row)">催签</el-button>
                <el-button link type="danger" @click="revokeSign(row)">撤回</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 已完成 -->
        <el-tab-pane label="已完成" name="completed">
          <el-table :data="completedList" stripe>
            <el-table-column prop="documentName" label="文档名称" width="200" />
            <el-table-column prop="documentType" label="文档类型" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.documentType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="initiator" label="发起人" width="120" />
            <el-table-column prop="completeTime" label="完成时间" width="180" />
            <el-table-column prop="totalSigners" label="签署人数" width="100" align="center">
              <template #default="{ row }">
                {{ row.totalSigners }}人
              </template>
            </el-table-column>
            <el-table-column prop="validity" label="有效性" width="120" align="center">
              <template #default="{ row }">
                <el-tag :type="row.validity ? 'success' : 'danger'">
                  {{ row.validity ? '有效' : '无效' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewDocument(row)">查看</el-button>
                <el-button link type="success" @click="downloadDocument(row)">下载</el-button>
                <el-button link type="info" @click="verifySign(row)">验签</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 签章管理 -->
        <el-tab-pane label="签章管理" name="seal">
          <el-button type="primary" icon="Plus" @click="showSealDialog = true" style="margin-bottom: 15px">
            添加签章
          </el-button>

          <el-table :data="sealList" stripe>
            <el-table-column label="签章预览" width="150" align="center">
              <template #default="{ row }">
                <div class="seal-preview">
                  <img :src="row.sealImage" alt="签章" style="width: 80px; height: 80px" />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sealName" label="签章名称" width="150" />
            <el-table-column prop="sealType" label="签章类型" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.sealType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="owner" label="所有人" width="120" />
            <el-table-column prop="department" label="所属部门" width="150" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="usageCount" label="使用次数" width="100" align="center" />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === '启用' ? 'success' : 'info'">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="editSeal(row)">编辑</el-button>
                <el-button link type="warning" @click="toggleSealStatus(row)">
                  {{ row.status === '启用' ? '停用' : '启用' }}
                </el-button>
                <el-button link type="danger" @click="deleteSeal(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发起签署对话框 -->
    <el-dialog v-model="showSignDialog" title="发起签署" width="700px">
      <el-form :model="signForm" label-width="100px">
        <el-form-item label="文档名称">
          <el-input v-model="signForm.documentName" placeholder="请输入文档名称" />
        </el-form-item>
        <el-form-item label="文档类型">
          <el-select v-model="signForm.documentType" placeholder="请选择类型">
            <el-option label="合同" value="contract" />
            <el-option label="协议" value="agreement" />
            <el-option label="审批单" value="approval" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文档">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持pdf、doc、docx格式，单个文件不超过20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="签署人">
          <el-select v-model="signForm.signers" placeholder="请选择签署人" multiple>
            <el-option label="张三" value="zhangsan" />
            <el-option label="李四" value="lisi" />
            <el-option label="王五" value="wangwu" />
          </el-select>
        </el-form-item>
        <el-form-item label="签署顺序">
          <el-radio-group v-model="signForm.signOrder">
            <el-radio label="parallel">并行签署</el-radio>
            <el-radio label="sequential">顺序签署</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="截止时间">
          <el-date-picker
            v-model="signForm.deadline"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="说明">
          <el-input
            v-model="signForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSignDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSignSubmit">发起签署</el-button>
      </template>
    </el-dialog>

    <!-- 添加签章对话框 -->
    <el-dialog v-model="showSealDialog" title="添加签章" width="600px">
      <el-form :model="sealForm" label-width="100px">
        <el-form-item label="签章名称">
          <el-input v-model="sealForm.sealName" placeholder="请输入签章名称" />
        </el-form-item>
        <el-form-item label="签章类型">
          <el-select v-model="sealForm.sealType" placeholder="请选择类型">
            <el-option label="公司公章" value="company" />
            <el-option label="合同专用章" value="contract" />
            <el-option label="财务专用章" value="finance" />
            <el-option label="个人签名" value="personal" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="sealForm.department" placeholder="请选择部门">
            <el-option label="总经办" value="general" />
            <el-option label="财务部" value="finance" />
            <el-option label="法务部" value="legal" />
            <el-option label="销售部" value="sales" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传签章">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
          >
            <img v-if="sealForm.sealImage" :src="sealForm.sealImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSealDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSealSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 统计数据
const stats = reactive({
  totalDocuments: 28,
  myPendingSignatures: 5,
  completedSignatures: 156,
  rejectedSignatures: 3
})

// 当前标签页
const activeTab = ref('pending')

// 待签署列表
const pendingList = ref([
  {
    id: 1,
    documentName: '采购合同-办公设备',
    initiator: '张经理',
    documentType: '合同',
    sendTime: '2025-01-12 14:30',
    deadline: '2025-01-15 18:00',
    signType: '电子签章',
    urgency: '紧急'
  },
  {
    id: 2,
    documentName: '年度服务协议',
    initiator: '李主管',
    documentType: '协议',
    sendTime: '2025-01-11 10:00',
    deadline: '2025-01-16 18:00',
    signType: '电子签名',
    urgency: '普通'
  }
])

// 我发起的列表
const initiatedList = ref([
  {
    id: 1,
    documentName: '产品销售合同',
    documentType: '合同',
    createTime: '2025-01-10 09:00',
    signProgress: 75,
    signedCount: 3,
    totalSigners: 4,
    status: '签署中'
  },
  {
    id: 2,
    documentName: 'IT服务协议',
    documentType: '协议',
    createTime: '2025-01-08 15:30',
    signProgress: 50,
    signedCount: 1,
    totalSigners: 2,
    status: '签署中'
  }
])

// 已完成列表
const completedList = ref([
  {
    id: 1,
    documentName: '办公室租赁合同',
    documentType: '合同',
    initiator: '行政部',
    completeTime: '2025-01-08 16:45',
    totalSigners: 3,
    validity: true
  },
  {
    id: 2,
    documentName: '员工劳动合同',
    documentType: '合同',
    initiator: 'HR部',
    completeTime: '2025-01-05 11:20',
    totalSigners: 2,
    validity: true
  }
])

// 签章列表
const sealList = ref([
  {
    id: 1,
    sealName: '公司公章',
    sealType: '公司公章',
    sealImage: 'https://via.placeholder.com/80?text=SEAL',
    owner: '总经理',
    department: '总经办',
    createTime: '2024-01-15 10:00',
    usageCount: 328,
    status: '启用'
  },
  {
    id: 2,
    sealName: '合同专用章',
    sealType: '合同专用章',
    sealImage: 'https://via.placeholder.com/80?text=CONTRACT',
    owner: '法务主管',
    department: '法务部',
    createTime: '2024-02-20 14:30',
    usageCount: 156,
    status: '启用'
  }
])

// 对话框
const showSignDialog = ref(false)
const showSealDialog = ref(false)

// 表单
const signForm = reactive({
  documentName: '',
  documentType: '',
  signers: [],
  signOrder: 'parallel',
  deadline: '',
  description: ''
})

const sealForm = reactive({
  sealName: '',
  sealType: '',
  department: '',
  sealImage: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 方法
const getUrgencyType = (urgency) => {
  const types = {
    '紧急': 'danger',
    '普通': 'primary',
    '不紧急': 'info'
  }
  return types[urgency] || 'info'
}

const getStatusType = (status) => {
  const types = {
    '签署中': 'warning',
    '已完成': 'success',
    '已拒绝': 'danger',
    '已撤回': 'info'
  }
  return types[status] || 'info'
}

const handleTabClick = (tab) => {
  console.log('切换标签页', tab.props.name)
}

const previewDocument = (row) => {
  console.log('预览文档', row)
  ElMessage.info('预览文档')
}

const signDocument = (row) => {
  console.log('签署文档', row)
  ElMessage.success('签署成功')
}

const rejectDocument = (row) => {
  ElMessageBox.prompt('请输入拒绝原因', '拒绝签署', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(({ value }) => {
    console.log('拒绝原因', value)
    ElMessage.success('已拒绝')
  }).catch(() => {})
}

const viewProgress = (row) => {
  console.log('查看进度', row)
  ElMessage.info('查看签署进度')
}

const downloadDocument = (row) => {
  console.log('下载文档', row)
  ElMessage.success('下载成功')
}

const urgeSign = (row) => {
  console.log('催签', row)
  ElMessage.success('催签消息已发送')
}

const revokeSign = (row) => {
  ElMessageBox.confirm('确定要撤回该签署请求吗？', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('已撤回')
  }).catch(() => {})
}

const viewDocument = (row) => {
  console.log('查看文档', row)
  ElMessage.info('查看文档')
}

const verifySign = (row) => {
  console.log('验签', row)
  ElMessage.success('签名有效')
}

const editSeal = (row) => {
  Object.assign(sealForm, row)
  showSealDialog.value = true
}

const toggleSealStatus = (row) => {
  const action = row.status === '启用' ? '停用' : '启用'
  ElMessageBox.confirm(`确定要${action}该签章吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    row.status = row.status === '启用' ? '停用' : '启用'
    ElMessage.success(`${action}成功`)
  }).catch(() => {})
}

const deleteSeal = (row) => {
  ElMessageBox.confirm('确定要删除该签章吗？', '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSignSubmit = () => {
  console.log('发起签署', signForm)
  ElMessage.success('签署请求已发送')
  showSignDialog.value = false
}

const handleSealSubmit = () => {
  console.log('添加签章', sealForm)
  ElMessage.success('签章添加成功')
  showSealDialog.value = false
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}
</script>

<style scoped lang="scss">
.electronic-signature-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .stat-icon {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    margin-right: 15px;
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.main-card {
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.seal-preview {
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>

